package net.hust.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


import net.hust.bean.User;
import net.hust.service.UserService;

@Service @Transactional
public class UserServiceBean implements UserService{

	@Resource SessionFactory factory;
	public void delete(String... usernames) {
		for(String username : usernames){
			factory.getCurrentSession().delete(factory.getCurrentSession().load(User.class, username));
		}
	}

	
	public void delete(int userId) {
		factory.getCurrentSession().delete(factory.getCurrentSession().load(User.class, userId));
	}


	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public User find(Integer userId ) {
		User user = (User)factory.getCurrentSession().get(User.class, userId);
		return user;
	}

	@SuppressWarnings("unchecked")
	@Transactional(propagation = Propagation.NOT_SUPPORTED)	
	public String findPwByNm(String username) {
		String password = null;
		String sql = "SELECT passwd  FROM _user WHERE user_name='" + username + "'";
		List<String> pws = factory.getCurrentSession().createSQLQuery(sql).list();
        
        password = pws.get(0);
		return password;
	}


	@SuppressWarnings("unchecked")
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public List<User> list() {
		// TODO Auto-generated method stub
		return factory.getCurrentSession().createQuery("from User").list();
	}

	public void save(User user) {
		factory.getCurrentSession().persist(user);
	}

	public void update(User user) {
		factory.getCurrentSession().merge(user);
	}

}
